package com.google.code.sfa.parse;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;

import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.db.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.symbol.*;

public class TraceConsensusParser {

    private XMLStreamReader parser;
    private String basename;
    private SymbolList consensus;

    public TraceConsensusParser( String basename) throws IOException {
	this.basename = basename;
	String filename = basename + "/assembly/ASSEMBLY.xml";
	try {
	    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	    InputStream is = new FileInputStream( filename);
	    parser = inputFactory.createXMLStreamReader( is);
	} catch ( XMLStreamException e) {
	    throw new IOException( e);
	}

    }


    public boolean parse() {
	try{ 
	    while( parser.hasNext() ) {
		int event = parser.next();
		switch( event) {
		case XMLStreamConstants.START_ELEMENT:
		    if( "consensus".equals( parser.getLocalName()) ) {
			try {
			    consensus = DNATools.createDNA( readText().replaceAll("\\s","") );
			    return true;
			} catch(IllegalSymbolException e) {
			    e.printStackTrace();
			    return false;
			}
		    }
		    break;
		}
	    }
	    return false;
	} catch( XMLStreamException e) {
	    e.printStackTrace();
	    return false;
	}
    }

    public SymbolList getConsensus() {
	return consensus;
    }

    private String readText() throws XMLStreamException {
	String text = "";
	while( parser.hasNext() ) {

	    int event = parser.next();
	    switch( event) {
	    case XMLStreamConstants.CHARACTERS:
		text += parser.getText();
		break;
	    case XMLStreamConstants.END_ELEMENT:
		return text;
	    }
	}
	return text;
    }

}